package cn.wzx.controller;

import cn.wzx.entity.Book;
import cn.wzx.entity.Largefile;
import cn.wzx.respJson.RespJson;
import cn.wzx.service.BookService;
import cn.wzx.service.BookTypeService;
import cn.wzx.service.LargefileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyEditorSupport;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@CrossOrigin // 允许跨域访问
@Controller
@RequestMapping("/api/adm/book")
public class BookController {
    @Autowired
    BookService bookService;
    @Autowired
    BookTypeService bookTypeService;

    @Autowired
    LargefileService largefileService;

    // 日期格式化
    @InitBinder
    public void initBinder(final WebDataBinder webdataBinder){
        webdataBinder.registerCustomEditor(Date.class, new PropertyEditorSupport(){
            @Override
            public void setAsText(String text) throws IllegalArgumentException{
                if (text.indexOf("-")>0){
                    if (text.indexOf("")<1){
                        text = text + " 00:00:00";
                    }
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd" +
                            "HH:mm:ss");
                    try {
                        Date d = sdf.parse(text);
                        setValue(d);
                    }catch (Exception e){
                        System.out.println("书本日期错误...." + text );
                        setValue(new Date()); //毫秒
                    }
                }else {
                    setValue(new Date(Long.valueOf(text))); //毫秒
                }
            }
        });
    }

    // 书本全查询
    @ResponseBody
    @RequestMapping("/findAll")
    public Map<String,Object> findAll(){
        return RespJson.pack(200,"OK",bookService.findAll());
    }

    // 根据id查找书本
    @ResponseBody
    @RequestMapping("/findById/{id}")
    public Map<String,Object> findById(@PathVariable("id") Integer id){
        return RespJson.pack(200,"OK",bookService.findById(id));
    }

    //分页功能 start 页数  num 一页的行数
    @ResponseBody
    @RequestMapping({"/findByPage/{start}/{num}"})
    public Map<String, Object> findByPage(@PathVariable("start") Integer start, @PathVariable("num") Integer num) {
        Map<String, Object> map = new HashMap<>();
        List<Book> lst = bookService.findByPage(start - 1, num);
        map.put("books", lst);
        // 计算出总页数
        int count = bookService.count();
        map.put("total", count);
        return RespJson.pack(200, "", map);
    }

    // 添加书本
    @ResponseBody
    @RequestMapping({"/addBook"})
    public Map<String, Object> addBook(Book book,Largefile largefile,@RequestParam(value = "pic", required = false) MultipartFile file){
        Map<String,Object> map = new HashMap<>();
        String msg = "操作失败";
        // 如果id=0并且有图片传入，就执行书本添加功能
        if (book.getId() == null && book.getId() == 0){
            if (file != null && file.getSize() > 0){
                try {
                    String uuid = UUID.randomUUID().toString();
                    book.setPicture(uuid);
                    largefile.setId(uuid);
                    largefile.setFilename(file.getOriginalFilename());
                    largefile.setContent(file.getBytes());
                    largefileService.add(largefile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            bookService.add(book);
            msg = "添加书本成功";
        }
        // 如果传入的书本id 是某本书的 id ，就执行修改书本功能
        if (book.getId() != null && book.getId() > 0){
            if (file != null && file.getSize() > 0){
                try {
                    largefileService.delById(book.getPicture());
                    String uuid = UUID.randomUUID().toString();
                    book.setPicture(uuid);
                    largefile.setId(uuid);
                    largefile.setFilename(file.getOriginalFilename());
                    largefile.setContent(file.getBytes());
                    largefileService.add(largefile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            bookService.update(book);
            msg = "书本更新成功";
        }
        // 查询该本书并返回给前端
        book = bookService.findById(book.getId());
        map.put("book",book);
        return RespJson.pack(200,msg,map);
    }


    // 书本图片显示功能，根据 id 来找到图片并显示
    @ResponseBody
    @RequestMapping({"/show/{id}"})
    public void show(@PathVariable String id, HttpServletResponse response) {
        System.out.println("id====" + id);
        if (id == null) return;
        Largefile byId = largefileService.findById(id);
        if (byId != null) {
            byte[] buf = (byte[]) byId.getContent();
            try {
                response.setContentType("image/jpeg");
                response.getOutputStream().write(buf);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
